package com.juntuo.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.StringUtil;
import com.juntuo.cache.LocalCache;
import com.juntuo.entity.Device;
import com.juntuo.entity.DeviceHistory;
import com.juntuo.entity.DeviceHistoryAdjust;
import com.juntuo.entity.ParkConclude;
import com.juntuo.platformUtils.QueryDeviceDataUtil;
import com.juntuo.service.DeviceHistoryAdjustService;
import com.juntuo.service.DeviceHistoryService;
import com.juntuo.service.DeviceService;
import com.juntuo.service.ParkConcludeService;
import com.juntuo.websocket.SpringWebSocketHandler;
import com.juntuo.youbo.AuthenticationUtil4Youbo;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 简介：
 * 作者：Jason (chenxj@hadlinks.com)
 * 时间：2018/4/8 15:51
 */
@Controller
@RequestMapping("/callback")
public class CallBackController {
    Logger log=Logger.getLogger(CallBackController.class);
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceHistoryService deviceHistoryService;
    @Autowired
    private ParkConcludeService parkConcludeService;
    @Autowired
    private DeviceHistoryAdjustService deviceHistoryAdjustService;

    @Bean//这个注解会从Spring容器拿出Bean
    public SpringWebSocketHandler infoHandler() {
        return new SpringWebSocketHandler();
    }


    @ResponseBody
    @RequestMapping("/device/add")
    public void deviceAdded(@RequestBody Map<String,Object> deviceMap) throws Exception {
        log.info(JSON.toJSONString(deviceMap));
        String deviceId = (String)deviceMap.get("deviceId");
        Map<String,Object> deviceInfo = (Map<String,Object>)deviceMap.get("deviceInfo");
        if(StringUtil.isNotEmpty(deviceId) && deviceInfo!=null){
            Device device = new Device();
            device.setDeviceId(deviceId);
            Device device1=deviceService.selectOne(device);
            if(device1==null){
                device=QueryDeviceDataUtil.query(deviceId);
                device.setCreateTime(new Date());
//                QueryDeviceDataUtil.query(deviceId);
//                device.setName((String)deviceInfo.get("name"));
                deviceService.insert(device);

            }else{
                log.info(deviceId+" 该设备已经存在！");
            }
        }
    }

    /**
     * 这个方法必须存在
     */
    @ResponseBody
    @RequestMapping("/device/data")
    public void deviceDataChange(@RequestBody Map<String,Object> deviceMap) throws Exception {
        log.info("data change :" + JSON.toJSONString(deviceMap));
        String deviceId = (String) deviceMap.get("deviceId");
        DeviceHistory lastHistory = LocalCache.getHistoryValue(deviceId);
        Map<String, Object> service = (Map<String, Object>) deviceMap.get("service");
        Device device = new Device();
        device.setDeviceId(deviceId);
//        boolean needBreak=false;
        String serviceId = (String) service.get("serviceId");
        Map<String, Object> data = (Map<String, Object>) service.get("data");
        switch (serviceId) {
            case "VehicleDetectorBasic":
                Integer sequence = (Integer) data.get("sequence");
                if (sequence==null ){//过滤掉没有sequence的和重复发的
                    log.info("deviceId:"+deviceId+"---no sequence");
//                        needBreak=true;
                    break;
                }
                if(sequence==1){
                    DeviceHistory deviceHistory4delete = new DeviceHistory();
                    deviceHistory4delete.setDeviceId(deviceId);
                    deviceHistoryService.delete(deviceHistory4delete);
                    lastHistory=null;
                }
                if(lastHistory!=null){
                    if(sequence<=lastHistory.getSequence()){
                        log.info("deviceId:"+deviceId+"---sequence<=lastHistory.getSequence");
                        break;
                    }
                }

                device.setSequence(sequence);
                String status = (String) data.get("status");

                device.setStatus(status);
                device.setParkNumber((String) data.get("NO"));
                if ("1".equals(status)) {
                    device.setSignalStrength((Integer) data.get("signalStrength"));
                    device.setSignalStrength((Integer) data.get("signalStrength"));
                } else {
                    if (data.get("latitude") != null) {
                        device.setLatitude(Double.parseDouble(data.get("latitude").toString()));
                    }
                    if (data.get("longitude") != null) {
                        device.setLongitude(Double.parseDouble(data.get("longitude").toString()));
                    }
                    //这段生成账单的 目前就航天通信使用
//                    for(int i =sequence-1;i>0;i--){
//                        DeviceHistory deviceHistory0 = new DeviceHistory();
//                        //先从缓存取 缓存没有再查询
//                        if(lastHistory!=null&&lastHistory.getSequence()==i){
//                            deviceHistory0 = lastHistory;
//                        }else{
//                            deviceHistory0.setDeviceId(deviceId);
//                            deviceHistory0.setSequence(i);
//                            List<DeviceHistory> histories0 = deviceHistoryService.select(deviceHistory0);
//                            if(histories0!=null && histories0.size()>0){
//                                deviceHistory0=histories0.get(0);
//
//                            }
//                        }
//                        if(deviceHistory0!=null && "1".equals(deviceHistory0.getStatus()) ){
//                            ParkConclude parkConclud = new ParkConclude();
//                            parkConclud.setDeviceId(deviceId);
//                            parkConclud.setParkNumber(device.getParkNumber());
//                            Date startTime = deviceHistory0.getCreateTime();
//                            parkConclud.setStartTime(startTime);
//                            Date endTime  = new Date();
//                            parkConclud.setEndTime(endTime);
//                            if(endTime.getTime()-startTime.getTime()>5*60*1000){
//                                parkConclud.setTotalTime((endTime.getTime()-startTime.getTime())/(1000*60*60.0));
//                                parkConcludeService.insert(parkConclud);
//                            }
//
//                            i=0;
//                        }
////                            deviceHistory0= deviceHistoryService.selectOne(deviceHistory0);
//
//                    }
                }
                DeviceHistory deviceHistory = new DeviceHistory();
                BeanUtils.copyProperties(device, deviceHistory);
                deviceHistory.setId(null);
                deviceHistory.setCreateTime(new Date());
                deviceHistory.setUpdateTime(new Date());
                deviceHistory.setTrustRatio(100);
                boolean needFilter=false;
                if(lastHistory!=null&&status.equals(lastHistory.getStatus())){
                    deviceHistory.setTrustRatio(50);
                    needFilter=true;
                }
                deviceHistoryService.insert(deviceHistory);

                LocalCache.putHistoryValue(deviceId,deviceHistory);
                //发送给其他人
                if(!needFilter){
                    //这一段暂时只有优泊使用 先写死了
                    if("266ef583-b32b-4006-b94f-aef3a7923809".equals(deviceId)||
                            "6d98dbc9-edec-40da-a957-dc790b90791e".equals(deviceId)||
                            "538c6dc1-af61-4f4b-8244-275d5d7d02e4".equals(deviceId)||
                            "18cca20e-fb69-48dc-acc8-6c5f53943f63".equals(deviceId)
//                                || "36402361-6c0a-48c7-8820-6504f57a83d5".equals(deviceId)
                            ){
                        Device device11 = new Device();
                        device11.setDeviceId(deviceId);
                        device11=deviceService.selectOne(device11);
                        deviceHistory.setBatteryLevel(device11.getBatteryLevel());
                        DeviceHistoryAdjust adjust = new DeviceHistoryAdjust();
                        BeanUtils.copyProperties(deviceHistory,adjust);
                        String token = LocalCache.getTokenValue("ybAccessToken");
                        String res = AuthenticationUtil4Youbo.updateData(token,deviceHistory);
                        if(StringUtil.isNotEmpty(res)){
                            Map<String,Object> mm = (Map<String,Object>)JSON.parse(res);
                            if(1!=Integer.parseInt(mm.get("status_code").toString())){
                                token = AuthenticationUtil4Youbo.login();
                                res=AuthenticationUtil4Youbo.updateData(token,deviceHistory);
                                if(StringUtil.isNotEmpty(res)){
                                    Map<String,Object> mm1 = (Map<String,Object>)JSON.parse(res);
                                    if(1==Integer.parseInt(mm1.get("status_code").toString())) {
                                        deviceHistoryAdjustService.insert(adjust);
                                    }
                                }
                            }else{
                                deviceHistoryAdjustService.insert(adjust);
                            }
                        }else{
                            token = AuthenticationUtil4Youbo.login();
                            LocalCache.putTokenValue("ybAccessToken",token);
                            res=AuthenticationUtil4Youbo.updateData(token,deviceHistory);
                            if(StringUtil.isNotEmpty(res)){
                                Map<String,Object> mm2 = (Map<String,Object>)JSON.parse(res);
                                if(1==Integer.parseInt(mm2.get("status_code").toString())) {
                                    deviceHistoryAdjustService.insert(adjust);
                                }
                            }
                        }
                    }
                }
                infoHandler().sendMessageToUsers(new TextMessage(JSON.toJSONString(device)));
                break;
            case "Battery":
                device.setBatteryLevel((Integer) data.get("batteryLevel"));
                break;
            default:
                break;
        }
        device.setUpdateTime(new Date());
        log.info("device-----" + JSON.toJSONString(device));
        deviceService.updateByDeviceIdSelective(device);
    }

    @ResponseBody
    @RequestMapping("/updateDeviceDatas")
    public void deviceDatasChange(@RequestBody Map<String,Object> deviceMap) throws Exception {
        log.info("data change :" + JSON.toJSONString(deviceMap));
//        String deviceId = (String) deviceMap.get("deviceId");
//        DeviceHistory lastHistory = LocalCache.getHistoryValue(deviceId);
//        List<Map<String, Object>> services = (List<Map<String, Object>>) deviceMap.get("services");
//        Device device = new Device();
//        device.setDeviceId(deviceId);
////        boolean needBreak=false;
//        for (Map<String, Object> service : services) {
//            String serviceId = (String) service.get("serviceId");
//            Map<String, Object> data = (Map<String, Object>) service.get("data");
//            switch (serviceId) {
//                case "VehicleDetectorBasic":
//                    Integer sequence = (Integer) data.get("sequence");
//                    if (sequence==null ){//过滤掉没有sequence的和重复发的
////                        needBreak=true;
//                        break;
//                    }
//                    if(sequence==1){
//                        DeviceHistory deviceHistory4delete = new DeviceHistory();
//                        deviceHistory4delete.setDeviceId(deviceId);
//                        deviceHistoryService.delete(deviceHistory4delete);
//                    }
//                    if(lastHistory!=null){
//                        if(sequence<=lastHistory.getSequence()){
//                            break;
//                        }
//                    }
//
//                    device.setSequence(sequence);
//                    String status = (String) data.get("status");
//
//                    device.setStatus(status);
//                    device.setParkNumber((String) data.get("NO"));
//                    if ("1".equals(status)) {
//                        device.setSignalStrength((Integer) data.get("signalStrength"));
//                        device.setSignalStrength((Integer) data.get("signalStrength"));
//                    } else {
//                        if (data.get("latitude") != null) {
//                            device.setLatitude(Double.parseDouble(data.get("latitude").toString()));
//                        }
//                        if (data.get("longitude") != null) {
//                            device.setLongitude(Double.parseDouble(data.get("longitude").toString()));
//                        }
//                        //这段生成账单的 目前就航天通信使用
//                        for(int i =sequence-1;i>0;i--){
//                            DeviceHistory deviceHistory0 = new DeviceHistory();
//                            //先从缓存取 缓存没有再查询
//                            if(lastHistory!=null&&lastHistory.getSequence()==i){
//                                deviceHistory0 = lastHistory;
//                            }else{
//                                deviceHistory0.setDeviceId(deviceId);
//                                deviceHistory0.setSequence(i);
//                                List<DeviceHistory> histories0 = deviceHistoryService.select(deviceHistory0);
//                                if(histories0!=null && histories0.size()>0){
//                                    deviceHistory0=histories0.get(0);
//
//                                }
//                            }
//                            if(deviceHistory0!=null && "1".equals(deviceHistory0.getStatus()) ){
//                                ParkConclude parkConclud = new ParkConclude();
//                                parkConclud.setDeviceId(deviceId);
//                                parkConclud.setParkNumber(device.getParkNumber());
//                                Date startTime = deviceHistory0.getCreateTime();
//                                parkConclud.setStartTime(startTime);
//                                Date endTime  = new Date();
//                                parkConclud.setEndTime(endTime);
//                                if(endTime.getTime()-startTime.getTime()>5*60*1000){
//                                    parkConclud.setTotalTime((endTime.getTime()-startTime.getTime())/(1000*60*60.0));
//                                    parkConcludeService.insert(parkConclud);
//                                }
//
//                                i=0;
//                            }
////                            deviceHistory0= deviceHistoryService.selectOne(deviceHistory0);
//
//                        }
//
//
//                    }
//                    DeviceHistory deviceHistory = new DeviceHistory();
//                    BeanUtils.copyProperties(device, deviceHistory);
//                    deviceHistory.setId(null);
//                    deviceHistory.setCreateTime(new Date());
//                    deviceHistory.setUpdateTime(new Date());
//                    deviceHistory.setTrustRatio(100);
//                    boolean needFilter=false;
//                    if(lastHistory!=null&&status.equals(lastHistory.getStatus())){
//                        deviceHistory.setTrustRatio(50);
//                        needFilter=true;
//                    }
//                    deviceHistoryService.insert(deviceHistory);
//
//                    LocalCache.putHistoryValue(deviceId,deviceHistory);
//                    //发送给其他人
//                    if(!needFilter){
//                        //这一段暂时只有优泊使用 先写死了
//                        if("266ef583-b32b-4006-b94f-aef3a7923809".equals(deviceId)||
//                                "6d98dbc9-edec-40da-a957-dc790b90791e".equals(deviceId)||
//                                "538c6dc1-af61-4f4b-8244-275d5d7d02e4".equals(deviceId)||
//                                "18cca20e-fb69-48dc-acc8-6c5f53943f63".equals(deviceId)
////                                || "36402361-6c0a-48c7-8820-6504f57a83d5".equals(deviceId)
//                                ){
//                            Device device11 = new Device();
//                            device11.setDeviceId(deviceId);
//                            device11=deviceService.selectOne(device11);
//                            deviceHistory.setBatteryLevel(device11.getBatteryLevel());
//                            DeviceHistoryAdjust adjust = new DeviceHistoryAdjust();
//                            BeanUtils.copyProperties(deviceHistory,adjust);
//                            String token = LocalCache.getTokenValue("ybAccessToken");
//                            String res = AuthenticationUtil4Youbo.updateData(token,deviceHistory);
//                            if(StringUtil.isNotEmpty(res)){
//                                Map<String,Object> mm = (Map<String,Object>)JSON.parse(res);
//                                if(1!=Integer.parseInt(mm.get("status_code").toString())){
//                                    token = AuthenticationUtil4Youbo.login();
//                                    res=AuthenticationUtil4Youbo.updateData(token,deviceHistory);
//                                    if(StringUtil.isNotEmpty(res)){
//                                        Map<String,Object> mm1 = (Map<String,Object>)JSON.parse(res);
//                                        if(1==Integer.parseInt(mm1.get("status_code").toString())) {
//                                            deviceHistoryAdjustService.insert(adjust);
//                                        }
//                                    }
//                                }else{
//                                    deviceHistoryAdjustService.insert(adjust);
//                                }
//                            }else{
//                                token = AuthenticationUtil4Youbo.login();
//                                LocalCache.putTokenValue("ybAccessToken",token);
//                                res=AuthenticationUtil4Youbo.updateData(token,deviceHistory);
//                                if(StringUtil.isNotEmpty(res)){
//                                    Map<String,Object> mm2 = (Map<String,Object>)JSON.parse(res);
//                                    if(1==Integer.parseInt(mm2.get("status_code").toString())) {
//                                        deviceHistoryAdjustService.insert(adjust);
//                                    }
//                                }
//                            }
//                        }
//                    }
//                    infoHandler().sendMessageToUsers(new TextMessage(JSON.toJSONString(device)));
//                    break;
//                case "Battery":
//                    device.setBatteryLevel((Integer) data.get("batteryLevel"));
//                    break;
//                default:
//                    break;
//            }
//        }
//        device.setUpdateTime(new Date());
//        log.info("device-----" + JSON.toJSONString(device));
//        deviceService.updateByDeviceIdSelective(device);
    }
    @ResponseBody
    @RequestMapping("/updateDeviceInfo")
    public void deviceinfoChange(@RequestBody Map<String,Object> deviceMap) throws Exception {
        log.info(JSON.toJSONString(deviceMap));
        String deviceId = (String)deviceMap.get("deviceId");
        Map<String,Object> deviceInfo = (Map<String,Object>)deviceMap.get("deviceInfo");
        if(StringUtil.isNotEmpty(deviceId) && deviceInfo!=null){
            Device device = new Device();
            device.setDeviceId(deviceId);
            Device device1=deviceService.selectOne(device);
            if(device1!=null){
                device=QueryDeviceDataUtil.query(deviceId);
                device.setId(device1.getId());
                deviceService.updateByPrimaryKeySelective(device1);
            }else{
                log.info("本地不存在该设备");
            }
        }
    }
    @ResponseBody
    @RequestMapping("/deletedDevice")
    public void deviceDataChage11(@RequestBody Map<String,Object> deviceMap){
        log.info(JSON.toJSONString(deviceMap));
        String deviceId = (String) deviceMap.get("deviceId");
        Device device = new Device();
        device.setDeviceId(deviceId);
        deviceService.delete(device);
    }

    @ResponseBody
    @RequestMapping("/reportCmdExecResult")
    public void cmdResult(@RequestBody Map<String,Object> map){
        log.info(JSON.toJSONString(map));
    }

}
